var ctx = window.daijia.ctx;
var map = null; // 地图对象
var offset = 0;
var limit = 5;
var pagingLimit = 5;// 显示分页时的条数
var currentTotalElements = 0;// 当前显示总条数
var pageLoading = true;// 是否能滚动加载
var hasShowPages = false;// 是否已显示分页
var firstLoadPages = true;// 分页初始化时 不自动加载
var thisButton;

$(document).ready(function() {

	// 选择公司查询
	if (document.getElementById("companyId")){
		$("#companyId").on("change", function (e) {
			var companyId = $("#companyId").val();
			if (companyId && companyId != null && companyId !="") {
				initdata(false, companyId);
			} else {
				initdata(false);
			}
		})
	}

	// 默认第一个业务选中
	$("#serviceType li:eq(0)").addClass("active");
	$("#contType li:eq(0)").addClass("active");

	// 点击加载不同的业务和终端的新闻
	$("#serviceType li").click(function (e) {
		var $this = $(this);
		$this.siblings().removeClass("active");
		$this.addClass("active");
		$("#contType li").siblings().removeClass("active");
		$("#contType li:eq(0)").addClass("active");
		if (document.getElementById("companyId")) {
			var companyId = $("#companyId").val();
			if (companyId && companyId != null && companyId !="") {
				initdata(false, companyId);
			} else {
				initdata(false);
			}
		} else {
			initdata(false);
		}
	})
	$("#contType li").click(function (e) {
		var $this = $(this);
		$this.siblings().removeClass("active");
		$this.addClass("active");
		if (document.getElementById("companyId")) {
			var companyId = $("#companyId").val();
			if (companyId && companyId != null && companyId !="") {
				initdata(false, companyId);
			} else {
				initdata(false);
			}
		} else {
			initdata(false);
		}
	})

	initdata(false);

	//删除新闻
	$(document).on("click",".deletethis",function(){
		thisButton = $(this);
		var confirm = $.scojs_confirm({
			content: "你真的要删除该新闻吗？",
			action:deleteNews
		});
		confirm.show();
	});

	function deleteNews() {
		$.get(ctx+'/news/deleteNews',{'id':thisButton.attr("id")},function(data){
			if(data.success){
				thisButton.parent().parent().remove();
				$.scojs_message('新闻删除成功', $.scojs_message.TYPE_OK);
				setTimeout(function(){
					window.location.reload(true);
				}, 800);
			} else {
				$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
			}
		},'json');
	}

	//置顶新闻
	$(document).on("click", ".topthis", function(){
		thisButton = $(this);
		var confirm = $.scojs_confirm({
			content: "你真的要置顶该新闻吗？",
			action:topNews
		});
		confirm.show();
	});

	function topNews() {
		$.get(ctx+'/news/topNews', {'id':thisButton.attr("id")}, function(data){
			if(data.success){
				thisButton.parent().parent().remove();
				$.scojs_message('置顶成功', $.scojs_message.TYPE_OK);
				setTimeout(function(){
					window.location.reload(true);
				}, 800);
			} else {
				$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
			}
		}, 'json');
	}

});


// 查询
$(document).on("keydown", "body", function() {
	if (window.event.keyCode == 13) {
		$("#searchButton").click();
	}
});

function initdata(isappend, companyId) {
	$('#loading').modal('show');
	// 获取服务类型
	var serviceType = $("#serviceType").find('li[class=active] a').attr('data');
	// 获取终端类型
	var contType = $("#contType").find('li[class=active] a').attr('data');

	$.ajax({
		url : ctx + '/news/listData',
		type : 'GET',
		async : false,
		dataType : 'json',
		 data : {
			 "pager.offset":offset,
			 "limit":limit,
			 'serviceType' : serviceType,
			 'contType' : contType,
			 'companyId' : companyId ? companyId : null
		},
		success : function(result) {
			$('#loading').modal('hide');
			console.debug(result);
			var newcontent = '';
			var totalElements = result.totalElements;
			$("#NoData").text("");
			if (totalElements > 0) {
				$(result.content).each(function(index, data) {
					var selectButton = "";
					selectButton += "<a href='"+ctx+"/news/look/"+data.id+"' class='btn-link modifyCash'>查看</a>";
					selectButton += "<a href='"+ctx+"/news/detail/"+data.id+"' class='btn-link modifyCash'>编辑</a>";
					if (data.status==1) {
						selectButton += "<a href='#' id='"+ data.id+ "' class='btn-link modifyCash topthis'>置顶</a>";
					}
					selectButton += "<a href='#' id='"+ data.id+ "' class='btn-link modifyCash deletethis'>删除</a>";
					
					var status="<span style='color:block;'>未置顶</span>";
					if (data.status==2) {
						status="<span style='color:green;'>已置顶</span>";
					}
					var link = data.link;
					if (data.link == null || data.link == '') {
						link = '内容广告无链接';
					} else {
						if (link.length > 30) {
							link = link.substring(0, 30) + "......"
						}
					}
					var title = data.title
					if (title == null || title == "") {
						title = "无标题"
					} else if (title.length > 20) {
						title = title.substring(0, 20) + "......"
					}
					newcontent += 
						"<tr class='grid-data tr-hui'  >"
							+ "<td>"+ status+ "</td>"
							+ "<td><div style='width:80px;height:50px;'><img style='width:100%;height:100%;' src='" + (ctx + data.image) +"'/></div></td>"
							+ "<td>"+ title+ "</td>"
							+ "<td>"+ link + "</td>"
							+ "<td>"+ data.author+ "</td>"
							+ "<td>"+ data.company.companyName+ "</td>"
							+ "<td>"+ data.created+ "</td>"
							+ "<td>"+ selectButton+ "</td>"
						+ "</tr>";
				});

			} else {
				$("#NoData").text("当前页面暂无记录 ");
			}

			if (!isappend) {
				$("#news_tbody .grid-data").remove();
			}
			$("#news_tbody").append(newcontent);
			$("#news_tbody .grid-data").each(function(index, element) {
				$(element).fadeIn(200 + (index * 35));
			});

			if (!hasShowPages) {
				if (!isappend) {
					currentTotalElements = result.content.length;
					pageLoading = true;
				} else {
					if (currentTotalElements < totalElements) {
						currentTotalElements += result.content.length;
						pageLoading = true;
					} else {
						pageLoading = false;
					}
				}
			}

			if (hasShowPages) {
				firstLoadPages = true;
				$(".pageshow li a").html("共" + totalElements + " 条数据");
				$(".pagedata").paging(totalElements,{
									format : '[< ncnnn >]',
									perpage : pagingLimit,
									page : (offset / limit) + 1,
									onSelect : function(page) {
										limit = pagingLimit;
										offset = (page - 1) * limit;
										if (!firstLoadPages) {
											initdata(false);
										}
										firstLoadPages = false;
										return false;
									},
									onFormat : function(type) {
										switch (type) {
										case 'block': // n and c
											if (!this.active)
												return '';
											else if (this.value != this.page)
												return '<li><a href="#">'
														+ this.value
														+ '</a></li>';
											return '<li class="active"><a href="#">'
													+ this.value
													+ '</a></li>';
										case 'next': // >
											return '<li><a href="#">&rsaquo;</a><li>';
										case 'prev': // <
											return '<li><a href="#">&lsaquo;</a><li>';
										case 'first': // [
											return '<li><a href="#">&laquo;</a><li>';
										case 'last': // ]
											return '<li><a href="#">&raquo;</a></li>';
										}
									}
								});
					} else {
						pageLoading = false;
						hasShowPages = true;
						$(".pageshow").show();
						$(".pagedata").show();
						$(".pageshow li a").html("共" + totalElements + " 条数据");
						$(".pagedata").paging(totalElements,{
							format : '[< ncnnn >]',
							perpage : pagingLimit,
							onSelect : function(page) {
								limit = pagingLimit;
								offset = (page - 1) * limit;
								if (!firstLoadPages) {
									initdata(false);
								}
								firstLoadPages = false;
								return false;
							},
							onFormat : function(type) {
								switch (type) {
								case 'block': // n and c
									if (!this.active)
										return '';
									else if (this.value != this.page)
										return '<li><a href="#">'
												+ this.value
												+ '</a></li>';
									return '<li class="active"><a href="#">'
											+ this.value
											+ '</a></li>';
								case 'next': // >
									return '<li><a href="#">&rsaquo;</a><li>';
								case 'prev': // <
									return '<li><a href="#">&lsaquo;</a><li>';
								case 'first': // [
									return '<li><a href="#">&laquo;</a><li>';
								case 'last': // ]
									return '<li><a href="#">&raquo;</a></li>';
								}
							}
						});
					}
				}
			});
}

Date.prototype.Format = function(fmt) {
	var o = {
		"M+" : this.getMonth() + 1, // 月份
		"d+" : this.getDate(), // 日
		"h+" : this.getHours(), // 小时
		"m+" : this.getMinutes(), // 分
		"s+" : this.getSeconds(), // 秒
		"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
		"S" : this.getMilliseconds()
	// 毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	for ( var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
}
